package com.example.scoredemo.dao;

import android.app.Application;
import android.content.Context;

import androidx.annotation.NonNull;
import androidx.room.Room;
import androidx.room.migration.Migration;
import androidx.sqlite.db.SupportSQLiteDatabase;

import com.example.scoredemo.dao.entity.Student;

import java.util.List;

/**
 * @author :muzi102
 * @time : 2021/3/27
 * @Description
 */
public class DaoUtil {
    private static MyDataBase myDataBase;
    private StudentDao studentDao;
    private static DaoUtil instance;
    private Application content;

    private DaoUtil(Application content) {
        this.content = content;
        myDataBase = Room.databaseBuilder((Context) content.getApplicationContext(), MyDataBase.class, "student_database")
//                .fallbackToDestructiveMigration()//破坏式迁移 即删除全部数据
                .addMigrations(MIGRATION_2_3)
                .build();
        studentDao = myDataBase.getStudentDao();
    }

    public static DaoUtil getInstance(Application content) {

        if (instance == null) {
            synchronized (DaoUtil.class) {
                if (instance == null) {
                    instance = new DaoUtil(content);
                }
            }
        }
        return instance;
    }

    /**
     * 增加字段
     */
    private static final Migration MIGRATION_1_2 = new Migration(1, 2) {
        @Override
        public void migrate(@NonNull SupportSQLiteDatabase database) {

            database.execSQL("ALTER TABLE Student ADD COLUMN age INTEGER NOT NULL DEFAULT 0");
        }
    };
    /**
     * 增加字段
     */
    private static final Migration MIGRATION_2_3 = new Migration(2, 3) {
        @Override
        public void migrate(@NonNull SupportSQLiteDatabase database) {
            database.execSQL("ALTER TABLE Student ADD COLUMN student_address VARCHAR");
        }
    };
    /**
     * 删除字段
     */
    private static final Migration MIGRATION_3_4 = new Migration(3, 4) {
        @Override
        public void migrate(@NonNull SupportSQLiteDatabase database) {
            /**
             * 1.创建新的表格
             * 2.复制数据
             * 3.删掉原来的
             * 4.更换名字
             */
        }
    };


    /**
     * 添加学生
     *
     * @param students
     */
    public void insertStduent(Student... students) {
        studentDao.insertStduent(students);
    }

    /**
     * 更新学生的资料
     *
     * @param students
     */
    public void updateStudent(Student... students) {
        studentDao.updateStudent(students);
    }


    /**
     * 删除学生
     *
     * @param students
     */
    public void deleteStudent(Student... students) {
        studentDao.deleteStudent(students);
    }


    /**
     * 删除全部的学生
     */
    public void deleteAllStudents() {
        studentDao.deleteAllStudents();
    }

    /**
     * 查询所有的学生
     */
    public List<Student> getAllStudents() {
        return studentDao.getAllStudents();
    }


}
